package org.misty.seckill.config;

import org.misty.seckill.rabbitmq.Queues;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

@Configuration
public class MqConfigurer {
  public static final String QUEUE = "queue";
  public static final String TOPIC_1 = "topic.1";
  public static final String TOPIC_2 = "topic.2";
  public static final String TOPIC_EXCHANGE = "topicExchange";
  public static final String TOPIC_ROUTING_KEY_1 = "topic.key1";
  public static final String TOPIC_ROUTING_KEY_ANY = "topic.#";
  public static final String FANOUT_EXCHANGE = "fanoutExchange";
  public static final String HEADERS_EXCHANGE = "headersExchange";
  public static final String HEADERS_QUEUE = "headersQueue";

  @Bean
  public Queue seckillQueue() {
    return new Queue(Queues.SECKILL, true);
  }




  /*-------------- Direct 模式----------------*/

  @Bean
  public Queue queue() {
    return new Queue(QUEUE, true);
  }

  /*-------------- Topic 模式----------------*/
  @Bean
  public Queue topic1() {
    return new Queue(TOPIC_1, true);
  }

  @Bean
  public Queue topic2() {
    return new Queue(TOPIC_2, true);
  }

  @Bean
  public TopicExchange topicExchange() {
    return new TopicExchange(TOPIC_EXCHANGE);
  }

  @Bean
  public Binding topicBinding1() {
    return BindingBuilder.bind(topic1()).to(topicExchange()).with(TOPIC_ROUTING_KEY_1);
  }

  @Bean
  public Binding topicBinding2() {
    return BindingBuilder.bind(topic2()).to(topicExchange()).with(TOPIC_ROUTING_KEY_ANY);
  }

  /*-------------- Fanout 模式(广播)----------------*/
  @Bean
  public FanoutExchange fanoutExchange() {
    return new FanoutExchange(FANOUT_EXCHANGE);
  }

  @Bean
  public Binding fanoutBinding1() {
    return BindingBuilder.bind(topic1()).to(fanoutExchange());
  }

  @Bean
  public Binding fanoutBinding2() {
    return BindingBuilder.bind(topic2()).to(fanoutExchange());
  }

  /*-------------- Header 模式(校验)----------------*/

  @Bean
  public HeadersExchange headersExchange() {
    return new HeadersExchange(HEADERS_EXCHANGE);
  }

  @Bean
  public Queue headersQueue() {
    return new Queue(HEADERS_QUEUE);
  }

  @Bean
  public Binding headersBinding() {
    var map = new HashMap<String, Object>();
    map.put("header1", "value1");
    map.put("header2", "value2");
    return BindingBuilder.bind(headersQueue()).to(headersExchange()).whereAll(map).match();
  }
}
